import { Form, Input, Modal, message } from 'antd'
import type { Rule } from 'antd/es/form'
import { useEffect } from 'react'

export interface FormItemConfig {
  name: string
  label: string
  placeholder?: string
  componentType?: 'input' | 'password' | 'email' | 'textarea'
  rules?: Rule[]
  componentProps?: Record<string, unknown>
}

export interface DialogFormProps<T extends Record<string, unknown> = Record<string, unknown>> {
  formItems: FormItemConfig[]
  open?: boolean
  title?: string
  loading?: boolean
  initialValues?: T
  onCancel?: () => void
  onOk?: (values: T) => void
  onValuesChange?: (changedValues: Partial<T>, allValues: T) => void
}

// 组件映射
const formComponents = {
  input: Input,
  password: Input.Password,
  email: Input,
  textarea: Input.TextArea,
}

export default function DialogForm<T extends Record<string, unknown> = Record<string, unknown>>({
  formItems,
  open,
  title = '表单对话框',
  loading = false,
  initialValues,
  onCancel,
  onOk,
  onValuesChange,
}: DialogFormProps<T>) {
  const [form] = Form.useForm()

  const handleAfterClose = () => {
    form.resetFields()
  }

  const handleOk = async () => {
    try {
      const values = await form.validateFields()
      onOk?.(values)
      onCancel?.() // 验证通过后关闭弹窗
    } catch (error: unknown) {
      // 验证失败时显示错误信息
      const formError = error as { errorFields?: Array<{ errors?: string[] }> }
      if (formError?.errorFields?.[0]?.errors?.[0]) {
        message.error(formError.errorFields[0].errors[0])
      }
    }
  }

  const handleCancel = () => {
    onCancel?.()
  }

  const handleChanges = (changedValues: Partial<T>, allValues: T) => {
    const data = onValuesChange?.(changedValues, allValues)
    console.log('🚀 ~ handleChanges ~ data:', data)
    if (data && data.type === 'update') {
      form.setFieldsValue({ ...allValues, ...data.data })
    }
  }
  useEffect(() => {
    if (open) {
      if (initialValues) {
        form.setFieldsValue(initialValues)
      } else {
        form.resetFields()
      }
    } else {
      form.resetFields()
    }
  }, [open, initialValues, form])
  return (
    <Modal
      title={title}
      open={open}
      onOk={handleOk}
      onCancel={handleCancel}
      afterClose={handleAfterClose}
      confirmLoading={loading}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={initialValues}
        onValuesChange={handleChanges}
      >
        {formItems.map(item => {
          const componentType = item.componentType || 'input'
          const Component = formComponents[componentType as keyof typeof formComponents]

          const componentProps = {
            placeholder: item.placeholder,
            ...(componentType === 'email' && { type: 'email' }),
            ...item.componentProps,
          }

          return (
            <Form.Item key={item.name} name={item.name} label={item.label} rules={item.rules}>
              <Component {...componentProps} />
            </Form.Item>
          )
        })}
      </Form>
    </Modal>
  )
}
